﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Threading.Tasks;
using tencentyun;

namespace TimServerSDK.Core
{
    public class RestSharpRestClientProvider : IRestClientProvider
    {
        protected readonly IServiceProvider ServiceProvider;

        public RestSharpRestClientProvider(IServiceProvider serviceProvider)
        {
            ServiceProvider = serviceProvider;
        }

        public async Task<TResult> PostAsync<TResult>(string servicename, string command, object input)
        {
            var optionsFun = ServiceProvider.GetRequiredService<ITimServerOptionsFun>();
            var options = await optionsFun.GetOptionsAsync();

            var sdkappid = options.AppId;
            var secretKey = options.AppSecret;
            var identifier = options.Identifier;
            var sigApi = new TLSSigAPIv2(sdkappid, secretKey);
            string userSig = sigApi.GenSig(identifier);

            var ran = new Random();
            var random = ran.Next(0);
            var baseUrl = "https://console.tim.qq.com";
            var client = new RestClient($"{baseUrl}/v4/{servicename}/{command}?sdkappid={sdkappid}&identifier={identifier}&usersig={userSig}&random={random}&contenttype=json");
            var request = new RestRequest();
            request.AddHeader("Content-Type", "application/json");

            var settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;

            var json = JsonConvert.SerializeObject(input, settings);
            request.AddParameter("application/json", json, ParameterType.RequestBody);


            var response = await client.PostAsync<TResult>(request);
            return response;
        }
    }
}
